import logging

import g4f

from .base import Chat
from .config import GPT4CHAT_CONFIG, SYSTEM_PROMPT


logger = logging.getLogger("chat")
g4f.logging = True # enable logging
g4f.check_version = False # Disable automatic version checking


class GPT4Chat(Chat):

    def __init__(self, name="gpt4"):
        super().__init__(name=name)
        logger.info("GPT4Chat initialized.")

    def chat(self, question):
        logger.info(f"{GPT4CHAT_CONFIG['debug']=}")
        logger.info(f"{question=}")
        question = SYSTEM_PROMPT + question

        if not GPT4CHAT_CONFIG["debug"]:
            try:
                answer = g4f.ChatCompletion.create(
                    model=g4f.models.gpt_4,
                    messages=[{"role": "user", "content": question}],
                )  # alternative model setting
            except RuntimeError as e:
                logger.error(f"RuntimeError: {e}")
                answer = "API报错，请忽略此回答"
            if "<title>人机验证</title>" in answer:
                logger.warning(f"Human machine verification")
                answer = "API返回人机验证页面，请忽略此回答"
        else:
            answer = "Text text here because debug=True"
        logger.info(f"{answer[:50]=}")
        return answer

